#pragma once
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <thread>
#include <string>
#include <atomic>
#include <mutex>
#include <queue>

namespace WD{

class WebSocketClient {
public:
    enum class Status {
        Disconnected,
        Connecting,
        Open,
        Failed,
        Closed
    };
    explicit WebSocketClient(boost::asio::io_context& ioc);
    ~WebSocketClient();

    bool connect(const std::string &host,
                 const std::string &port = "8080",
                 const std::string &path = "/jsonrpc");
    void send(const std::string& message);
    std::string receive(); // non-blocking receive
    void close();

    Status getStatus() const;
 
private:
    void readLoop();

    boost::asio::io_context& ioc_;
    boost::asio::ip::tcp::resolver resolver_;
    boost::beast::websocket::stream<boost::asio::ip::tcp::socket> ws_;

    std::thread reader_;
    std::atomic<bool> running_;
    std::atomic<Status> status_;

    std::mutex msg_mutex_;
    std::queue<std::string> msg_queue_;
};

}//namespace wd